﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Caliburn.Micro;
using GTServices.Model;

namespace GTServices.WPF.Client.ViewModels
{
    public class OptionsViewModel : Screen
    {
        public String DefaultDatabase { get; set; }
        public bool ReuseCodeWindows { get; set; }
        public bool UpdateOnAdd { get; set; } 

        public void SelecteDatabaseFile()
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".mdf";
            dlg.Filter = "DatabaseFiles (.mdf)|*.mdf";
            if (dlg.ShowDialog() == true)
            {
                DefaultDatabase = dlg.FileName;
            }
        }

        public void Save()
        {
            try
            {
                Validate();
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show(e.Message); 
                return; 
            }
            //Save the Settings in the basic model. 
            GTServices.Model.Properties.Settings.Default.DefaultDatabase = DefaultDatabase;
            GTServices.Model.Properties.Settings.Default.Save(); 
            //Save the Settings in thew View. 

            Properties.Settings.Default.ReuseCodeViewWindow = this.ReuseCodeWindows;
            Properties.Settings.Default.UpdateOnAdd = this.UpdateOnAdd;
            Properties.Settings.Default.Save(); 

            TryClose(true);
        }


        public void Validate()
        {
            if (!System.IO.File.Exists(DefaultDatabase))
            {
                throw new ArgumentException("Default database file does not exist"); 
            }
        }

        public void Cancel()
        {
            TryClose(false); 
        }

        public OptionsViewModel()
        {
            DefaultDatabase = GTServices.Model.Properties.Settings.Default.DefaultDatabase;

            ReuseCodeWindows = Properties.Settings.Default.ReuseCodeViewWindow;
            this.UpdateOnAdd = Properties.Settings.Default.UpdateOnAdd;
            NotifyOfPropertyChange(() => DefaultDatabase);
            NotifyOfPropertyChange(() => ReuseCodeWindows);
            NotifyOfPropertyChange(() => UpdateOnAdd);

            this.DisplayName = "Options";
            NotifyOfPropertyChange(() => DisplayName);
        }
    }
}
